<template>
	<view class="container">
	  <text class="tip-word" v-if="status === 'waiting'">正在支付，请稍候 ...</text>
	  <text class="tip-word green" v-if="status === 'success'">恭喜您，支付成功</text>
	  <text class="tip-word red" v-if="status === 'fail'">支付失败</text>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				status: 'waiting',
			}
		},
		onLoad(options) {
			// options 中含有订单号orderId和returnUrl,successUrl
			// const data = JSON.parse(decodeURIComponent(options.params || '') || '{}');
			const data = JSON.parse(options.params ? decodeURIComponent(options.params) : '{}');
			const openId = uni.getStorageSync('yeyuMiniOpenId');
			const {
				// api = '/app/order/pay',
				api = '/app/orderPayRecord/c2b/c2bCreateOrderPayRecord',
				token = '',
				apiServer = 'appserver',
				openIdLabel = 'openId', // openId 字段的label值
				returnUrl = '',  // 返回地址
				successUrl = '',  // 成功的跳转地址
				...otherParams
			} = data;
			
			this.status = 'waiting';
			
			this.$request(api, {
				headerToken: token,
				apiServer,
				params: {
					[openIdLabel]: openId,
					payTypeInt: 4,
					type: 'xcx',
					...otherParams,
				},
				success: res => {
					const data = res.body || {};
					const payInfo = data.payInfo || {};
					const payParams = {
						"appId": payInfo.appId,       //公众号名称，由商户传入
						"timeStamp": payInfo.timeStamp, //时间戳，自1970年以来的秒数     
						"nonceStr": payInfo.nonceStr, //随机串     
						"package": payInfo.package,
						"signType": payInfo.signType,  //微信签名方式：     
						"paySign": payInfo.paySign,     //微信签名
					};
					uni.requestPayment({
						...payParams,
						success: res => {
							this.status = 'success';
							uni.showToast({
								title: '支付成功',
								duration: 1000,
								success: () => {
									setTimeout(() => {
										if (successUrl) {
											uni.redirectTo({
												url: `/pages/index/index?redirect=${successUrl}`,
											})
										}
									}, 1000)
								}
							})
						},
						fail: res => {
							this.status = 'fail';
							uni.showToast({
								title: '支付失败',
								icon: 'none',
								success: () => {
									setTimeout(() => {
										if (returnUrl) {
											uni.redirectTo({
												url: `/pages/index/index?redirect=${returnUrl}`,
											})
										} else {
											uni.navigateBack();
										}
									}, 1500)
								},
							})
						}
					})
					
				},
				fail: res => {
					
				}
			});
		},
		methods: {
			
		}
	}
</script>

<style lang="scss">
	.container {
		text-align: center;
		padding-top: 200upx;
		overflow: hidden;
		
		.tip-word {
			
		}
		
		.green {
		  color: green;
		}
		.red {
		  color: red;
		}
	}
</style>
